package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void addCategory(CategoryDTO categoryDTO) {
        // 将dto转换为entity
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        //将信息补充完整
        category.setStatus(StatusConstant.DISABLE);
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.addCategory(category);
    }

    @Override
    public PageResult getPage(CategoryPageQueryDTO categoryPageQueryDTO) {
        //启用PageHelper
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        //调用函数
        List<Category> list=categoryMapper.getPage(categoryPageQueryDTO);
        //封装解析
        Page<Category> p= (Page<Category>) list;
        //返回PageResult对象
        return new PageResult(p.getTotal(),p.getResult());
    }

    @Override
    public void changeStatus(Integer status, Long id) {
        Category build = Category.builder()
                .status(status)
                .id(id)
                .build();
        categoryMapper.update(build);
    }

    @Override
    public void changeInfo(CategoryDTO categoryDTO) {
        Category category=new Category();
        //将categoryDTO复制到category
        BeanUtils.copyProperties(categoryDTO,category);
        category.setStatus(StatusConstant.DISABLE);

        categoryMapper.update(category);
    }

    @Override
    public void delete(Long id) {
        categoryMapper.delete(id);
    }

    @Override
    public List<Category> getByType(Integer type) {
        List<Category> categories=categoryMapper.getByType(type);
        return categories;
    }

}
